package com.qy.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qy.entity.AiChatMessage;
import com.qy.entity.UserCommProfile;
import com.qy.factory.ChatServiceFactory;
import com.qy.mapper.UserCommProfileMapper;
import com.qy.model.ChatMessageRequest;
import com.qy.model.ChatRequest;
import com.qy.service.IAiChatMessageService;
import com.qy.service.IChatService;
import com.qy.service.ISseService;
import com.qy.service.ITaocanService;
import com.qy.util.SSEUtil;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SseServiceImpl implements ISseService {

    private final ChatServiceFactory chatServiceFactory;

    private final IAiChatMessageService aiChatMessageService;
    
    private final ITaocanService taocanService;

    @Override
    public SseEmitter sseChat(ChatRequest chatRequest) {
        SseEmitter sseEmitter = new SseEmitter(0L);
        try {
            // 获取前端输入的content内容，分析用户名字并查询用户信息
            String content = chatRequest.getContent();
            String recommendPromot = taocanService.taocanRecommend(content);


            if ("error".equalsIgnoreCase(recommendPromot)) {
//                sseEmitter.send("请不要问其他的");
//                sseEmitter.complete();
            }else{
                chatRequest.setContent(recommendPromot);
            }

            // 构建消息列表
            buildChatMessageList(chatRequest);
            // 设置对话角色
            chatRequest.setRole("user");

            IChatService chatService = chatServiceFactory.getChatService(chatRequest.getModel());

            AiChatMessage aiChatMessage = new AiChatMessage();
            aiChatMessage.setSessionId(chatRequest.getSessionId());
            aiChatMessage.setRole("user");
            aiChatMessage.setContent(chatRequest.getContent());
            aiChatMessage.setModel(chatRequest.getModel());

//            aiChatMessageService.saveMessage(aiChatMessage);
            chatService.chat(chatRequest, sseEmitter);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            SSEUtil.sendErrorEvent(sseEmitter, e.getMessage());
        }
        return sseEmitter;
    }

    @Override
    public Flux<String> streamChat(ChatRequest chatRequest) {
        // 构建消息列表
        buildChatMessageList(chatRequest);
        IChatService chatService = chatServiceFactory.getChatService(chatRequest.getModel());

        AiChatMessage aiChatMessage = new AiChatMessage();
        aiChatMessage.setSessionId(chatRequest.getSessionId());
        aiChatMessage.setRole("user");
        aiChatMessage.setContent(chatRequest.getContent());
        aiChatMessage.setModel(chatRequest.getModel());

        aiChatMessageService.saveMessage(aiChatMessage);
        return chatService.streamChat(chatRequest);
    }

    @Override
    public Flux<ChatResponse> streamMessage(ChatMessageRequest request) {
        IChatService chatService = chatServiceFactory.getChatService(request.getModel());

        AiChatMessage aiChatMessage = new AiChatMessage();
        aiChatMessage.setSessionId(request.getSessionId());
        aiChatMessage.setRole("user");
        aiChatMessage.setContent(request.getContent());
        aiChatMessage.setModel(request.getModel());

        aiChatMessageService.saveMessage(aiChatMessage);
        return chatService.streamMessage(request);
    }

    @Override
    public Flux<ServerSentEvent<String>> mcpChat(ChatMessageRequest request) {
        IChatService chatService = chatServiceFactory.getChatService(request.getModel());
        AiChatMessage aiChatMessage = new AiChatMessage();
        aiChatMessage.setSessionId(request.getSessionId());
        aiChatMessage.setRole("user");
        aiChatMessage.setContent(request.getContent());
        aiChatMessage.setModel(request.getModel());

        aiChatMessageService.saveMessage(aiChatMessage);
        return chatService.mcpChat(request);
    }

    /**
     * 构建消息列表
     */
    private void buildChatMessageList(ChatRequest chatRequest) {
        List<ChatMessage> messages = new ArrayList<>();

        messages.add(new SystemMessage("你是一个给用户推荐套餐的AI助手，能够以对话的方式回应用户。请提供详细且准确的信息。当用户需要你推荐套餐时，只需要从指定的套餐列表中给出套餐和理由即可，不要进行提问。"));

        messages.add(new UserMessage(chatRequest.getContent()));
        chatRequest.setMessages(messages);
    }
    

}
